using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Deployment.Application;

namespace hosted_gmail_client
{
    public partial class Frame2 : Form
    {
        private string password;
        private string emailaddress;
        private bool hide = true;
        private bool alreadyupdated = false;
        private bool alreadychecked = false;
        private bool alreadyrestarted = false;
        private int numtries = 0;
        private int secondsloading = 0;
        private Timer loadingtimer = new Timer();
        private Timer avoidwarningtimercalendar = new Timer();
        private Compose frmCompose;
        ApplicationDeployment ad;

        public Frame2()
        {
            InitializeComponent();
            if (ApplicationDeployment.IsNetworkDeployed) {
               ad = ApplicationDeployment.CurrentDeployment;
               ad.CheckForUpdateCompleted += new CheckForUpdateCompletedEventHandler(ad_CheckForUpdateCompleted);
               ad.UpdateProgressChanged += new DeploymentProgressChangedEventHandler(ad_UpdateProgressChanged);
               ad.UpdateCompleted += new AsyncCompletedEventHandler(ad_UpdateCompleted);
            }
        }

        #region "Events"
        private void linkLabel1_LinkClicked_1(object sender, LinkLabelLinkClickedEventArgs e)
        {
            ShowGmail();
        }

        private void linkLabel2_LinkClicked_1(object sender, LinkLabelLinkClickedEventArgs e)
        {
            ShowCalendar();
        }

        private void pictureBox2_Click(object sender, EventArgs e)
        {
            ShowGmail();
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            ShowCalendar();
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            frmCompose = new Compose();
            frmCompose.Show();
        }

       private void toolStripButton4_Click(object sender,EventArgs e) {
          ShowLoading(true);
          wbGmail.Navigate("http://mail.google.com/hosted/" + emailaddress.Split(Char.Parse("@"))[1] + "/");
       }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            ShowLoading(true);
            wbGmail.Navigate("http://mail.google.com/hosted/" + emailaddress.Split(Char.Parse("@"))[1] + "/?view=cl&fs=1");
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            ShowLoading(true);
            wbGmail.Navigate("http://mail.google.com/hosted/" + emailaddress.Split(Char.Parse("@"))[1] + "/?view=pr&fs=1");
        }

        private void importContactsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ImportContacts frmImportContacts = new ImportContacts();
            frmImportContacts.Show();
        }

        private void checkForUpdatesToolStripMenuItem_Click(object sender, EventArgs e)
        {
           if (!alreadychecked) {
              if (ApplicationDeployment.IsNetworkDeployed) {
                 alreadychecked = true;
                 ad.CheckForUpdateAsync();
              } else {
                 MessageBox.Show("You cannot check for updates with the USB version.\nPlease check for updates at http://code.google.com/p/hosted-gmail-client");
              }
              
           } 
        }

        private void ad_UpdateCompleted(object sender, AsyncCompletedEventArgs e)
        {
            if (!alreadyrestarted)
            {
                alreadyrestarted = true;
                hide = false;
                Application.Restart();
            }
        }

        //to show the progressbar
        private void ad_UpdateProgressChanged(object sender, DeploymentProgressChangedEventArgs e)
        {
            this.progressBar1.Visible = true;
            this.progressBar1.Value = e.ProgressPercentage;
            if (e.ProgressPercentage == 100)
            {
                this.progressBar1.Visible = false;
            }
        }

        private void ad_CheckForUpdateCompleted(object sender, CheckForUpdateCompletedEventArgs e)
        {
            if (e.UpdateAvailable)
            {
                if (!alreadyupdated)
                {
                    alreadyupdated = true;
                    ad.UpdateAsync();
                }
            }
            else
            {
                MessageBox.Show("There are no updates availabile.");
                alreadyupdated = false;
                alreadychecked = false;
                alreadyrestarted = false;
            }
        }

        private void notifyIcon1_DoubleClick(object sender, EventArgs e)
        {
            ShowApplication();
        }

        private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (Options frmOptions = new Options())
            {
                frmOptions.ShowDialog();
                if (frmOptions.AccountChanged && frmOptions.DialogResult == DialogResult.OK)
                {
                    Logout frmLogOut = new Logout(1);
                    Logout frmLogOut2 = new Logout(2);
                    frmLogOut.ShowDialog();
                    frmLogOut2.ShowDialog();
                    if (frmLogOut.DialogResult == DialogResult.OK && frmLogOut2.DialogResult == DialogResult.OK)
                    {
                        numtries = 0;
                        GetRegistryValues();
                        LoadContent();
                    }
                }
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            QuitApplication();
        }

        private void exitToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            QuitApplication();
        }

        private void documentationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Not yet implemented");
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Not yet implemented");
        }

        private void showToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowApplication();
        }

        private void Frame_Load(object sender, EventArgs e)
        {
           avoidwarningtimercalendar.Tick += new EventHandler(avoidwarningtimercalendar_Tick);
           avoidwarningtimercalendar.Interval = 5000;
           loadingtimer.Tick += new System.EventHandler(this.loadingtimer_Tick);
            
            using (RegistryKey key = Common.GetRegistryKey(false))
            {
                if (key.GetValue("emailaddress") != null && key.GetValue("password") != null)
                {
                    GetRegistryValues();

                    if (Common.AuthenticateUser(emailaddress, password))
                        LoadContent();
                    else
                        ShowLoginScreen();

                }
                else
                    ShowLoginScreen();
            }
        }

        private void Frame_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (hide)
            {
                this.Hide();
                e.Cancel = true;
            }
        }

        private void wbGmail_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (wbGmail.Document.GetElementById("userName") != null)
            {
                //auto-fill login screen for Gmail with registry values
                wbGmail.Document.GetElementById("userName").SetAttribute("value", emailaddress.Split(Char.Parse("@"))[0]);
                wbGmail.Document.GetElementById("password").SetAttribute("value", password);

                //auto-fill login screen for Google calendar with registry settinsg
                wbCalendar.Document.GetElementById("userName").SetAttribute("value", emailaddress.Split(Char.Parse("@"))[0]);
                wbCalendar.Document.GetElementById("password").SetAttribute("value", password);
                
                if (numtries < 2)
                {
                    //auto-submit gmail login page
                    mshtml.IHTMLWindow2 gmail = (mshtml.IHTMLWindow2)wbGmail.Document.Window.DomWindow;
                    gmail.execScript("setTimeout('document.forms[0].submit();',2000);", "javascript");
                     
                    //auto-submit gcalendar login page
                    mshtml.IHTMLWindow2 gcalendar = (mshtml.IHTMLWindow2)wbCalendar.Document.Window.DomWindow;
                    gcalendar.execScript("setTimeout('document.forms[0].submit();',2000);", "javascript");
                    
                    numtries++;
                }
            }
            if (wbGmail.Document.GetElementById("userName") == null && wbCalendar.Document.GetElementById("password") == null)
            {
                ShowLoading(false);
                ShowGmail();
                numtries = 0;
            }
        }

        private void lnkRetry_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            numtries = 0;
            LoadContent();
            ShowRetryLinks(false);
        }

        private void loadingtimer_Tick(object sender, EventArgs e)
        {
            secondsloading++;

            if (secondsloading > 10)
            {
               ShowRetryLinks(true);
            }
        }

        private void toolStripButton5_Click(object sender,EventArgs e) {
           wbCalendar.Navigate("javascript:void(_GenSettings());");
        }

        private void toolStrip2_ItemClicked(object sender,ToolStripItemClickedEventArgs e) {
           wbCalendar.Navigate("javascript:void(_SR_backToCalendar());");
        }

        private void toolStripButton7_Click(object sender,EventArgs e) {
           wbCalendar.Navigate("javascript:void(_CreateNewEvent());");
        }

        private void toolStripTextBox1_Enter(object sender,EventArgs e) {
           toolStripTextBox1.Text = "";
           toolStripTextBox1.ForeColor = Color.Black;
        }

        private void toolStripTextBox1_Leave(object sender,EventArgs e) {
           toolStripTextBox1.ForeColor = Color.DarkGray;
           if (toolStripTextBox1.Text == "") {
              toolStripTextBox1.Text = "Lunch at Red Lobster tomorrow at 1:30PM";
           }
        }

        private void toolStripTextBox1_KeyPress(object sender,KeyPressEventArgs e) {
           if (e.KeyChar == 13) {
              wbCalendar.Navigate("javascript:da(\"compose\",[\"ctext\",\"" + toolStripTextBox1.Text + "\"],La(\"Failed to quick add event\",Nq))");
              toolStripTextBox1.ForeColor = Color.DarkGray;
           }
        }

        private void wbCalendar_Navigating(object sender,WebBrowserNavigatingEventArgs e) {
           //this was to try and ignore that warning for ie7 users... so far, unsuccessful.
           //if (e.Url.AbsoluteUri == "http://www.google.com/calendar/hosted/" + emailaddress.Split(Char.Parse("@"))[1].ToString() + "/render") {
           //   avoidwarningtimercalendar.Start(); 
           //   //this is screwing up the navigate event for wbgmail too--- need to fix
           //   e.Cancel = true;
           //}
        }

        private void avoidwarningtimercalendar_Tick(object sender,EventArgs e) {
           avoidwarningtimercalendar.Stop();
           wbCalendar.Navigate("http://www.google.com/calendar/hosted/" + emailaddress.Split(Char.Parse("@"))[1].ToString() + "/render?ignoreversion",null,null,"User-Agent: Mozilla/4.0 (compatible; Hosted Gmail Client 1.0(MSIE 4.01); Windows NT; )\n\r");
        }

        #endregion

        private void GetRegistryValues()
        {
            using (RegistryKey key = Common.GetRegistryKey(false))
            {
                emailaddress = (string)key.GetValue("emailaddress");
                password = (string)key.GetValue("password");
            }
        }

        private void LoadContent()
        {
            ShowLoading(true);
            wbGmail.Navigate("http://mail.google.com/hosted/" + emailaddress.Split(Char.Parse("@"))[1].ToString() + "/");
            wbCalendar.Navigate("http://www.google.com/calendar/hosted/" + emailaddress.Split(Char.Parse("@"))[1].ToString() + "/render",null, null, "User-Agent: Mozilla/4.0 (compatible; Hosted Gmail Client 1.0(MSIE 4.01); Windows NT; )\r\n");
           
        }

        private void ShowLoginScreen()
        {
            using (Login frmLogin = new Login())
            {
                frmLogin.ShowDialog();
                GetRegistryValues();

                if (frmLogin.DialogResult == DialogResult.OK)
                    LoadContent();
                else
                    QuitApplication();
            }
        }

        private void QuitApplication()
        {
            hide = false;
            Application.Exit();
        }

        private void ShowApplication()
        {
            this.Show();
            this.Activate();

            if (this.WindowState == FormWindowState.Minimized)
                this.WindowState = FormWindowState.Normal;
        }

        private void ShowLoading(bool show)
        {
            pnlLoading.Visible = show;
            pnlLoading.BringToFront();

            if (show)
            {
                ShowRetryLinks(false);
                loadingtimer.Interval = 1000;
                loadingtimer.Start();
            }
            else
            {
                loadingtimer.Stop();
                secondsloading = 0;
                ShowGmail();
            }
        }

        private void ShowGmail()
        {
            if (!pnlLoading.Visible)
            {
                wbGmail.BringToFront();
                importContactsToolStripMenuItem.Enabled = true;
                ShowGmailToolbar();
            }
        }

        private void ShowGmailToolbar()
        {
            this.SuspendLayout();
            toolStrip2.Visible = false;
            toolStrip1.Visible = true;
            this.ResumeLayout();
        }

        private void ShowCalendar()
        {
            if (!pnlLoading.Visible)
            {
                wbCalendar.BringToFront();
                importContactsToolStripMenuItem.Enabled = true;
                ShowCalendarToolbar();
            }
        }

        private void ShowCalendarToolbar()
        {
            this.SuspendLayout();
            toolStrip1.Visible = false;
            toolStrip2.Visible = true;
            this.ResumeLayout();
        }


        private void ShowRetryLinks(bool show)
        {
            lnkRetry.Visible = show;
            secondsloading = 0;
        }

       
    }
}